﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include <iostream>

#include "SDL.h"
#include "SDL_image.h"
#include <string>
#undef main

void ApplySurface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = nullptr )
{
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;

    //Blit
    SDL_BlitSurface(source, clip, destination, &offset );
}

int main()
{
    //屏幕相关参数
    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;

    //图形表面
    SDL_Window *screen = nullptr;
    SDL_Surface *image = nullptr;
    SDL_Surface *dots = nullptr;

    //用于分片的数组
    SDL_Rect clip[4];

    //SDL事件对象
    SDL_Event event;
    bool quit = false;

    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        std::cout << SDL_GetError() << std::endl;
        return -1;
    }

    //创建窗口
    screen = SDL_CreateWindow("图片划分",
                              SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED,
                              SCREEN_WIDTH,
                              SCREEN_HEIGHT,
                              SDL_WINDOW_SHOWN
                              );
    if(screen == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
        return -1;
    }

    //获取窗口对应的surface
    image = SDL_GetWindowSurface(screen);
    SDL_FillRect(image, nullptr, 0xff009900);

    dots = IMG_Load("E://workspace//FFMEPG//SDL//sources//dots.png");
    if(dots == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }
    else
    {
        //去除图片背景色
        SDL_SetColorKey(dots, SDL_TRUE, SDL_MapRGB( dots->format, 0, 0xFF, 0xFF));
    }


    //Clip range for the top left
    clip[ 0 ].x = 0;
    clip[ 0 ].y = 0;
    clip[ 0 ].w = 100;
    clip[ 0 ].h = 100;

    //Clip range for the top right
    clip[ 1 ].x = 100;
    clip[ 1 ].y = 0;
    clip[ 1 ].w = 100;
    clip[ 1 ].h = 100;

    //Clip range for the bottom left
    clip[ 2 ].x = 0;
    clip[ 2 ].y = 100;
    clip[ 2 ].w = 100;
    clip[ 2 ].h = 100;

    //Clip range for the bottom right
    clip[ 3 ].x = 100;
    clip[ 3 ].y = 100;
    clip[ 3 ].w = 100;
    clip[ 3 ].h = 100;

    ApplySurface( 0, 0, dots, image, &clip[0]);
    ApplySurface( 540, 0, dots, image, &clip[1]);
    ApplySurface( 0, 380, dots, image, &clip[2]);
    ApplySurface( 540, 380, dots, image, &clip[3]);

    SDL_UpdateWindowSurface(screen);
    while (quit == false) //当用户不想退出时
    {
        //函数SDL_PollEvent() 的作用是从事件队列底部取出一个事件并将其事件数据粘贴到一个SDL_Event类型的结构体中
        while (SDL_PollEvent(&event))
        {
            //若用户点击量窗口右上角的关闭按钮
            if(event.type == SDL_QUIT)
            {
                //退出程序
                quit = true;
            }
        }
    }

    SDL_FreeSurface(image);
    image = nullptr;
    SDL_FreeSurface(dots);
    dots = nullptr;
    SDL_DestroyWindow(screen);
    screen = nullptr;
    SDL_Quit();
    return 0;
}
